import { useViewportStore } from '@/store/viewport'
import { ElLoading } from 'element-plus'
import { storeToRefs } from 'pinia'
import { ObjectLoader } from '@/utils/ObjectLoader'
import { nextTick } from 'vue'
import { useFocusObject } from '@/utils/useFocusObject'
import { useAddTools } from '@/utils/useAddTools'
import { getModelData } from '@/api/road'
import { CubeTextureLoader, MeshBasicMaterial, TextureLoader } from 'three'
import { type RoadObj } from '@/utils/findTrackPath'
import MyWork from '@/utils/webWork?worker'

const viewportStore = useViewportStore()
const { publicGroup } = storeToRefs(viewportStore)
const loader = new ObjectLoader()
const { focusObject } = useFocusObject()
const { hasGroup, createdLabel, createWorkFaces, createdTunnelLabel } = useAddTools()
const cubeTextureLoader = new CubeTextureLoader();
const BASE_URL = import.meta.env.BASE_URL
export default async function () {
  const sky = await cubeTextureLoader.loadAsync([
    BASE_URL + 'materials/sky.jpg',
    BASE_URL + 'materials/sky.jpg',
    BASE_URL + 'materials/sky.jpg',
    BASE_URL + 'materials/sky.jpg',
    BASE_URL + 'materials/sky.jpg',
    BASE_URL + 'materials/sky.jpg'
  ])
  const texture = new TextureLoader().load(BASE_URL + 'materials/coal.jpg');
  const material = new MeshBasicMaterial({
    color: 0xffffff,
    transparent: true,
    envMap: sky,
    opacity: 0.5,
    side: 2,
  });
  const material1 = new MeshBasicMaterial({
    map: texture,
    side: 2,
    // wireframe: true,
    // color: 0x000000,
    // transparent: true,
    // envMap: sky,
    // opacity: 0.8,
  });

  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  // 获取模型数据
  const { data } = await getModelData()
  if (data.modelInfo && data.modelInfo[0]) {
    const sceneNodes = loader.parse(data.modelInfo[0])
    const curveList: RoadObj[] = []
    if (sceneNodes.children?.length && publicGroup.value) {
      publicGroup.value.add(...sceneNodes.children)

      publicGroup.value.children.forEach((group) => {
        if (group.name === '设备') {
          group.children.forEach((node) => {
            node.layers.set(3);
            const label = createdLabel(node)
            label.name = node.name
            node.add(label)
          })
        }
        if (group.name === '巷道') {
          // 巷道图层
          group.traverse((node) => {
            node.material = material
            if (node.userData.customData?.isTunnelling) {
              node.material = material1
              const label = createdTunnelLabel(node)
              label.name = node.name
              node.add(label)
            }

            if (node.geometry && node.geometry.type === "TunnelGeometry") {
              curveList.push({ uuid: node.uuid, name: node.name, curve: node.geometry.parameters.path.toJSON() })
            }
          })
          group.children.forEach((node) => {
            if (node.type === 'Group' && node.name.includes('采面') && node.children.length > 1) {
              createWorkFaces(node)
            }
          })
        }
      })
    }
    nextTick(() => {
      const worker = new MyWork();
      worker.postMessage([curveList, 1]);
      worker.onmessage = (e) => {
        console.log(e.data);
        const curveNetwork = e.data;
        viewportStore.setCurveNetwork(curveNetwork)
        localStorage.setItem('curveNetwork', JSON.stringify(curveNetwork))
      }
      loading.close()
      const group = hasGroup('巷道', false)
      if (group) {
        focusObject(group)
      }
    })
  } else {
    loading.close()
  }
}
